package org.yy.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.MultiValueMap;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class TokenFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();


        String path = request.getURI().getPath();
        if (path.startsWith("/api/user") || path.startsWith("/api/code")) {
            System.out.println("登录注册不拦截");
        } else {
            System.out.println("非登录注册过滤");
            MultiValueMap<String, HttpCookie> cookies = request.getCookies();
            System.out.println("cookies=" + cookies);
            List<HttpCookie> token = cookies.get("token");
            System.out.println("token=" + token);
            if (token == null) {
                String data = "被拦截,token={}";
                DataBuffer wrap = response.bufferFactory().wrap(data.getBytes());
                System.out.println(data);
                response.setStatusCode(HttpStatus.UNAUTHORIZED);

                String url = "/static/login.html";
                response.getHeaders().set(HttpHeaders.LOCATION, url);
                Mono<Void> voidMono = response.setComplete();
                return voidMono;
            }
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
